package com.young.shop.api.service.impl;


import com.young.shop.api.dao.MyCartsMapper;
import com.young.shop.api.service.MyCartsService;
import com.young.shop.pojo.entity.Order;
import com.young.shop.pojo.qo.CartsInfoQO;
import com.young.shop.pojo.vo.MyShopCartsVO;
import com.young.shop.pojo.vo.PayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class MyCartsServiceImpl implements MyCartsService {
    @Autowired
    private MyCartsMapper myCartsMapper;
    @Override
    public void insertGoods(int goodsId, int userId, int goodsNumber) {
        //插入购物车表信息
        int i = myCartsMapper.insertCart(goodsId, userId, goodsNumber);
        //根据userId查询购物车id
        if (i!=1){
            throw new RuntimeException("加入购物车失败，请重试");
        }
    }

    @Override
    public List<MyShopCartsVO> initCarts(int userId) {

        //查询购物车
        return  myCartsMapper.selectCartsByUserId(userId);

    }



    @Override
    public Long addOrder(CartsInfoQO[] cartsList) {


        Integer totalNumber = cartsList[0].getCheckNum();
        BigDecimal totalMoney = cartsList[0].getTotalMoney();
        Integer userId = cartsList[0].getUserId();

        Order order = new Order();
        order.setQuantity(totalNumber);
        order.setOrderPrice(totalMoney);
        //插入订单
         myCartsMapper.insertOrder(order);
         //获取当前订单id
        Long oid = order.getOid();

        //插入订单-用户表
        myCartsMapper.insertUserOrders(oid.intValue(),userId);

        for (int i = 0; i < cartsList.length; i++) {
            Integer goodsId = cartsList[i].getGoodsId();
            Integer goodsNumber = cartsList[i].getGoodsNumber();
            Integer id = cartsList[i].getId();
            //插入order-goods表
            myCartsMapper.insertOrderGoods(goodsId,goodsNumber,oid.intValue());
            //删除订单
            myCartsMapper.delectCartsById(id);
        }

        return oid;
    }

    @Override
    public void removeOrder(int id) {
        myCartsMapper.delectCartsById(id);
    }

    @Override
    public List<PayVO> initPay(int orderId) {
        System.out.println("serviec的orderId："+orderId);
        //
        List<PayVO> payVOS = myCartsMapper.selectPayByOrderId(orderId);
        return payVOS;
    }


}
